//
//  YZArchieveOptionVC.m
//  VET
//
//  Created by 刘文靖 on 2018/7/15.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZArchieveOptionVC.h"
#import "YZArchieveOptionCell.h"
#import "YZSearchBar.h"
#import "MJExtension.h"
#import "YZPigModel.h"
#import "YZOptionBtn.h"
#import "YZSwineryModel.h"
#import "MJRefresh.h"
#import "YZWorkNoteModel.h"
@interface YZArchieveOptionVC ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSArray *models;
@property (nonatomic, strong) YZSearchBar *searchBar;
@property (nonatomic, strong) UILabel *selectedLabel;
@property (nonatomic, strong) UIButton *confirmBtn;
@property (nonatomic, assign) YZArchieveOptionType optionType;
@property (nonatomic, strong) NSString *searchStr;
@end

@implementation YZArchieveOptionVC
- (instancetype)initWithOptionType:(YZArchieveOptionType)optionType{
    self = [super init];
    if (self) {
        _tableView = [UITableView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _optionType = optionType;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem  = [self barButtonItemWithTitle:@"取消" titleColor:kColorWithHex(0x393939) target:self action:@selector(leftClicked)];
     [self setupMainView];
}

- (void)setupMainView{
    self.view.backgroundColor = kColorWithHex(0xE9EAEB);
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = kColorWithHex(0xffffff);
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.mas_equalTo(53);
    }];
    [bottomView addSubview:self.selectedLabel];
    [self.selectedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.offset(18);
    }];
    
    [bottomView addSubview:self.confirmBtn];
    [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(98, 44));
        make.top.offset(5);
        make.right.offset(-6);
    }];
    [self.confirmBtn addTarget:self action:@selector(confirmBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *headerView = [UIView new];
    headerView.height = 60;
    [headerView addSubview:self.searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.offset(12);
        make.right.offset(-12);
        make.height.mas_equalTo(36);
    }];
    _tableView.tableHeaderView = headerView;
   
    _tableView.rowHeight = 54;
    self.tableView.sectionIndexColor = [UIColor lightGrayColor];
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundView.backgroundColor = [UIColor clearColor];
    //_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableFooterView = [UIView new];
    _tableView.showsVerticalScrollIndicator = NO;
    [_tableView registerClass:[YZArchieveOptionCell class] forCellReuseIdentifier:@"YZArchieveOptionCell"];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.bottom.mas_equalTo(bottomView.mas_top).offset(-5);
    }];
    _dataSource = [NSMutableArray array];
    if (self.optionType == YZArchieveOptionPig) {
        self.title = @"选择猪只";
        self.searchBar.placeholder = @"输入猪只耳标号";
        self.selectedLabel.text = [NSString stringWithFormat:@"已选择：%lu只猪",(unsigned long)[self pigCount]];
    }else if (self.optionType == YZArchieveOptionPiggery){
        self.title = @"选择猪场";
        self.searchBar.placeholder = @"输入猪场的名字";
    }else if (self.optionType == YZArchieveOptionSwinery ||
              self.optionType == YZArchieveSingleSwinery ){
        self.title = @"选择猪群";
        self.searchBar.placeholder = @"输入猪群批次号";
        self.selectedLabel.text = [NSString stringWithFormat:@"已选择：%lu个猪群",(unsigned long)[self swineryCount]];
    }
    [self setupRefresh];
}

- (void)setupRefresh {
    
    // 设置刷新控件
    @weakify(self)
    
    // header
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self loadNewData];
    }];
    self.tableView.mj_header = header;
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
    
    // footer
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        [self loadMoreData];
    }];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
}

- (void)loadNewData{
    if (self.optionType == YZArchieveOptionPig){
        @weakify(self)
        [[YZPigModelAPI requestSwineList:0 earMark:self.searchStr type:@"object"] subscribeNext:^(NSDictionary *dict) {
            @strongify(self)
            self.dataSource = [YZPigModel mj_objectArrayWithKeyValuesArray:dict[@"list"]];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
        }error:^(NSError * _Nullable error) {
            @strongify(self)
            [self.tableView.mj_header endRefreshing];
        }];
    }else if (self.optionType == YZArchieveOptionSwinery){
        @weakify(self)
        [[YZSwineryModelAPI requestSwineryList:0 batchNo:self.searchStr] subscribeNext:^(NSDictionary *dict) {
            @strongify(self)
            self.dataSource = [YZSwineryModel mj_objectArrayWithKeyValuesArray:dict[@"list"]];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
        }error:^(NSError * _Nullable error) {
            @strongify(self)
            [self.tableView.mj_header endRefreshing];
        }];
    } else if (self.optionType == YZArchieveSingleSwinery)  {
        
        @weakify(self)
        [[YZSwineryModelAPI requestSwineryList:0 batchNo:self.searchStr type:@"object"] subscribeNext:^(NSDictionary *dict) {
            @strongify(self)
            self.dataSource = [YZSwineryModel mj_objectArrayWithKeyValuesArray:dict[@"list"]];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
        }error:^(NSError * _Nullable error) {
            @strongify(self)
            [self.tableView.mj_header endRefreshing];
        }];
    } else {
        [self.tableView.mj_header endRefreshing];
    }
}

- (void)loadMoreData{
    
}

#pragma mark - getter && setter
-(YZSearchBar *)searchBar{
    if (!_searchBar){
        _searchBar = [[YZSearchBar alloc] init];
        _searchBar.backgroundColor = [UIColor clearColor];
        _searchBar.delegate = self;
        //光标颜色
        _searchBar.cursorColor = kColorWithHex(0x32BE60);
        //TextField
        _searchBar.searchBarTextField.layer.cornerRadius = 10;
        _searchBar.searchBarTextField.layer.masksToBounds = YES;
        _searchBar.searchBarTextField.layer.borderColor = kColorWithHex(0xFAFAFA).CGColor;
        _searchBar.searchBarTextField.layer.borderWidth = 1.0;
        _searchBar.searchBarTextField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        _searchBar.delegate = self;
        //去掉取消按钮灰色背景
        _searchBar.hideSearchBarBackgroundImage = YES;
    }
    return _searchBar;
}

- (UILabel *)selectedLabel{
    if (!_selectedLabel) {
        _selectedLabel = [[UILabel alloc] init];
        _selectedLabel.textColor = kColorWithHex(0x434343);
        _selectedLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    }
    return _selectedLabel;
}

- (UIButton *)confirmBtn{
    if (!_confirmBtn) {
        _confirmBtn = [[UIButton alloc] init];
        [_confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:kColorWithHex(0xffffff) forState:UIControlStateNormal];
        [_confirmBtn setBackgroundColor:kColorWithHex(0x2FC66A)];
        _confirmBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
        _confirmBtn.layer.cornerRadius = 4;
    }
    return _confirmBtn;
}

- (NSMutableArray *)selectedModels{
    if (!_selectedModels) {
        _selectedModels = [NSMutableArray array];
    }
    return _selectedModels;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZArchieveOptionCell *cell= [tableView dequeueReusableCellWithIdentifier:@"YZArchieveOptionCell"];
    cell.archieveModel = self.dataSource[indexPath.row];
    cell.optionBtn.selected = [self containsObejct:self.dataSource[indexPath.row] needUpdate:NO];
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YZArchieveOptionCell *cell = (YZArchieveOptionCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.optionBtn.selected = !cell.optionBtn.selected;
    [self containsObejct:self.dataSource[indexPath.row] needUpdate:YES];
    if (self.optionType == YZArchieveOptionPig){
        self.selectedLabel.text = [NSString stringWithFormat:@"已选择：%lu只猪",(unsigned long)[self pigCount]];
    } else if (self.optionType == YZArchieveOptionSwinery){
        self.selectedLabel.text = [NSString stringWithFormat:@"已选择：%lu个猪群",(unsigned long)[self swineryCount]];
    } else if (self.optionType == YZArchieveSingleSwinery) {
        
        // 猪只单选
        [self.selectedModels removeAllObjects];
        [self containsObejct:self.dataSource[indexPath.row] needUpdate:YES];
        self.selectedLabel.text = [NSString stringWithFormat:@"已选择：%lu个猪群",(unsigned long)self.selectedModels.count];
        [self.tableView reloadData];
    }
}

- (BOOL)containsObejct:(id)object needUpdate:(BOOL)update{
    if (self.optionType == YZArchieveOptionPig) {
        YZPigModel *model = (YZPigModel *)object;
        for (YZArchiveModel *archive in self.selectedModels) {
            if (archive.archiveId == model.pigId) {
                if (update) {
                    [self.selectedModels removeObject:archive];
                }
                return YES;
            }
        }
        if (update) {
            YZArchiveModel *archive = [YZArchiveModel convertWithPig:model];
            [self.selectedModels addObject:archive];
        }
        
    } else if (self.optionType == YZArchieveOptionSwinery ||
               self.optionType == YZArchieveSingleSwinery){
        YZSwineryModel *model = (YZSwineryModel *)object;
        for (YZArchiveModel *archive in self.selectedModels) {
            if (archive.archiveId == model.swineryId) {
                if (update) {
                    [self.selectedModels removeObject:archive];
                }
                return YES;
            }
        }
        if (update) {
            YZArchiveModel *archive = [YZArchiveModel convertWithSwinery:model];
            [self.selectedModels addObject:archive];
        }
    }
    
    
    return NO;
}

- (void)confirmBtnClicked{
    if (self.archieveSuccessBlock) {
        self.archieveSuccessBlock(self.selectedModels);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)leftClicked{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)pigCount{
    NSInteger count = 0;
    for (YZArchiveModel *archive in self.selectedModels){
        if ([archive.archiveType isEqualToString:@"swine"]) {
            ++count;
        }
    }
    return count;
}
- (NSInteger)swineryCount{
    NSInteger count = 0;
    for (YZArchiveModel *archive in self.selectedModels){
        if ([archive.archiveType isEqualToString:@"herd"]) {
            ++count;
        }
    }
    return count;
}
#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    self.searchStr = searchBar.text;
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
}

@end
